<template>
  <div class="job-posting-container">
    <!-- 头部操作栏 -->
    <div class="action-bar">
      <el-button type="primary" size="large" class="action-button" @click="showAddDialog">
        <i class="el-icon-plus"></i> 发布新职位
      </el-button>
      <el-button size="large" class="action-button" @click="goToHome">
        <i class="el-icon-back"></i> 返回主页
      </el-button>
    </div>

    <!-- 职位卡片列表 -->
    <div class="job-grid">
      <el-card
        v-for="job in jobPostings"
        :key="job.job_id"
        class="job-card"
        shadow="hover"
      >
        <template #header>
          <div class="card-header">
            <span class="job-title">{{ job.job_title }}</span>
            <div class="card-actions">
              <el-button type="primary" size="small" class="card-button edit-btn" @click="editJob(job)">
                编辑
              </el-button>
              <el-button type="danger" size="small" class="card-button delete-btn" @click="deleteJob(job.job_id)">
                删除
              </el-button>
              <el-button type="info" size="small" class="card-button view-app-btn" @click="toggleApps(job.job_id)">查看申请</el-button>
            </div>
          </div>
        </template>

        <div class="card-content">
          <p><strong>公司名称:</strong> {{ job.company_name }}</p>
          <p><strong>工作地点:</strong> {{ job.location }}</p>
          <p><strong>薪资范围:</strong> {{ job.salary_range || '面议' }}</p>
          <p><strong>职位状态:</strong> 
            <el-tag :type="job.is_open ? 'success' : 'info'">
              {{ job.is_open ? '招聘中' : '已结束' }}
            </el-tag>
          </p>
          <div class="job-description">
            <p><strong>职位描述:</strong></p>
            <p class="description-text">{{ job.job_description }}</p>
          </div>
          <div class="job-requirements">
            <p><strong>职位要求:</strong></p>
            <p class="description-text">{{ job.requirements }}</p>
          </div>
          <p class="update-time">发布时间: {{ formatDate(job.post_date) }}</p>
          <p v-if="job.expiration_date" class="update-time">截止日期: {{ formatDate(job.expiration_date) }}</p>
        </div>

        <div v-if="expanded[job.job_id]" class="application-section">
          <el-table :data="applications[job.job_id]" size="small" stripe>
            <el-table-column label="申请人" width="120">
              <template #default="{ row }">
                {{ userNames[row.applicant_id] || `用户${row.applicant_id}` }}
              </template>
            </el-table-column>
            <el-table-column prop="apply_time" label="时间" width="120">
              <template #default="{ row }">{{ formatDate(row.apply_time) }}</template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{ row }">
                <el-select v-model="row.status" @change="val => updateAppStatus(row.application_id, val)">
                  <el-option v-for="opt in statusOptions" :key="opt" :label="opt" :value="opt"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="{ row }">
                <el-button type="text" @click="viewResume(row.applicant_id)">查看简历</el-button>
                <el-button type="text" @click="openMessageDialog(row.applicant_id, job.job_id)">发消息</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 查看简历对话框 -->
          <el-dialog v-model="resumeDialogVisible" title="查看简历" width="50%">
            <div v-if="selectedResume">
              <p><strong>期望岗位:</strong> {{ selectedResume.desired_position }}</p>
              <p><strong>当前状态:</strong> {{ selectedResume.current_status }}</p>
              <p><strong>经验年限:</strong> {{ selectedResume.experience_years || '未填写' }} 年</p>
              <p><strong>期望薪资:</strong> {{ selectedResume.expected_salary || '未填写' }}</p>
              <p><strong>教育背景:</strong> {{ selectedResume.education_level || '未填写' }}</p>
              <p><strong>专业技能:</strong></p>
              <p class="skills-text">{{ selectedResume.skills || '未填写' }}</p>
              <p class="update-time">最后更新: {{ formatDate(selectedResume.last_updated) }}</p>
            </div>
            <div v-else class="no-resume-message">
              <el-empty description="求职者未发布简历！" />
            </div>
          </el-dialog>
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑职位弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="60%"
      class="job-dialog"
    >
      <el-form :model="currentJob" label-width="120px">
        <el-form-item label="职位名称" required>
          <el-input v-model="currentJob.job_title" placeholder="请输入职位名称" />
        </el-form-item>

        <el-form-item label="公司名称" required>
          <el-input v-model="currentJob.company_name" placeholder="请输入公司名称" />
        </el-form-item>

        <el-form-item label="工作地点" required>
          <el-input v-model="currentJob.location" placeholder="请输入工作地点" />
        </el-form-item>

        <el-form-item label="薪资范围">
          <el-input v-model="currentJob.salary_range" placeholder="例如：10k-15k" />
        </el-form-item>

        <el-form-item label="招聘状态">
          <el-switch
            v-model="currentJob.is_open"
            active-text="招聘中"
            inactive-text="已结束"
            :active-value="true"
            :inactive-value="false"
          />
        </el-form-item>

        <el-form-item label="截止日期">
          <el-date-picker
            v-model="currentJob.expiration_date"
            type="date"
            placeholder="选择截止日期"
          />
        </el-form-item>

        <el-form-item label="职位描述" required>
          <el-input
            v-model="currentJob.job_description"
            type="textarea"
            :rows="4"
            placeholder="请输入职位描述"
          />
        </el-form-item>

        <el-form-item label="职位要求" required>
          <el-input
            v-model="currentJob.requirements"
            type="textarea"
            :rows="4"
            placeholder="请输入职位要求"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button size="large" class="cancel-btn" @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" size="large" class="save-btn" @click="saveJob" :loading="loading">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 发消息对话框 -->
    <el-dialog title="发送消息" v-model="messageDialogVisible" width="40%">
      <el-form :model="messageForm" label-width="100px">
        <el-form-item label="消息内容" required>
          <el-input type="textarea" rows="4" v-model="messageForm.content" placeholder="请输入消息"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="messageDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="sendMessage">发送</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '../store/auth'

const router = useRouter()
const authStore = useAuthStore()
const loading = ref(false)

// 职位数据
const jobPostings = ref([])

// 当前操作的职位
const currentJob = ref({
  job_id: null,
  job_title: '',
  company_name: '',
  location: '',
  salary_range: '',
  job_description: '',
  requirements: '',
  is_open: true,
  expiration_date: null
})

// 弹窗控制
const dialogVisible = ref(false)
const dialogTitle = ref('发布新职位')
const isEditing = ref(false)

// 存储每个岗位的申请列表
const applications = reactive({})
const expanded = reactive({})
const statusOptions = ['已投递','已查看','面试中','已录用','已拒绝']

// 查看简历状态
const resumeDialogVisible = ref(false)
const selectedResume = ref(null)
const userNames = ref({})  // 新增：存储用户ID到用户名的映射
const messageDialogVisible = ref(false)  // 新增：消息对话框控制
const messageForm = ref({ content: '' })  // 新增：消息表单

// 获取职位列表
const fetchJobs = async () => {
  try {
    loading.value = true;
    
    const userId = authStore.userId || localStorage.getItem('user_id');
    if (!userId) {
      ElMessage.warning('请先登录');
      router.push('/login');
      return;
    }
    
    const token = authStore.token || localStorage.getItem('token');
    if (!token) {
      ElMessage.warning('认证失败，请重新登录');
      router.push('/login');
      return;
    }
    
    const response = await fetch(`http://127.0.0.1:8000/api/job-postings?user_id=${userId}`, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${encodeURIComponent(token)}`
      }
    })

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`获取职位失败: ${errorText}`)
    }

    jobPostings.value = await response.json()
  } catch (error) {
    ElMessage.error(error.message)
  } finally {
    loading.value = false;
  }
}

// 显示新增弹窗
const showAddDialog = () => {
  currentJob.value = {
    job_id: null,
    job_title: '',
    company_name: '',
    location: '',
    salary_range: '',
    job_description: '',
    requirements: '',
    is_open: true,
    expiration_date: null
  }
  dialogTitle.value = '发布新职位'
  isEditing.value = false
  dialogVisible.value = true
}

// 编辑职位
const editJob = (job) => {
  currentJob.value = { ...job }
  dialogTitle.value = '编辑职位'
  isEditing.value = true
  dialogVisible.value = true
}

// 保存职位
const saveJob = async () => {
  try {
    loading.value = true;
    
    // 验证必填字段
    if (!currentJob.value.job_title || !currentJob.value.company_name || 
        !currentJob.value.location || !currentJob.value.job_description || 
        !currentJob.value.requirements) {
      ElMessage.warning('请填写必填字段')
      loading.value = false;
      return;
    }

    const userId = authStore.userId || localStorage.getItem('user_id');
    if (!userId) {
      ElMessage.warning('用户未登录，请重新登录');
      router.push('/login');
      return;
    }
    
    const token = authStore.token || localStorage.getItem('token');
    if (!token) {
      ElMessage.warning('认证失败，请重新登录');
      router.push('/login');
      return;
    }

    const url = isEditing.value
      ? `http://127.0.0.1:8000/api/job-postings/${currentJob.value.job_id}`
      : 'http://127.0.0.1:8000/api/job-postings'

    const method = isEditing.value ? 'PUT' : 'POST'

    // 构建请求体，注意字段映射
    const requestBody = {
      ...currentJob.value,
      poster_id: parseInt(userId) // 后端会将poster_id映射到user_id
    };

    // 如果是编辑模式，确保包含job_id
    if (isEditing.value && !requestBody.job_id) {
      requestBody.job_id = currentJob.value.job_id;
    }

    console.log('发送请求体:', requestBody);

    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${encodeURIComponent(token)}`
      },
      body: JSON.stringify(requestBody)
    })

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`保存失败: ${errorText}`)
    }

    ElMessage.success(isEditing.value ? '更新成功' : '发布成功')
    dialogVisible.value = false
    fetchJobs()
  } catch (error) {
    ElMessage.error(error.message)
  } finally {
    loading.value = false;
  }
}

// 删除职位
const deleteJob = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个职位吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    loading.value = true;
    
    const userId = authStore.userId || localStorage.getItem('user_id');
    if (!userId) {
      ElMessage.warning('用户未登录，请重新登录');
      router.push('/login');
      return;
    }
    
    const token = authStore.token || localStorage.getItem('token');
    if (!token) {
      ElMessage.warning('认证失败，请重新登录');
      router.push('/login');
      return;
    }
    
    const response = await fetch(`http://127.0.0.1:8000/api/job-postings/${id}?user_id=${userId}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${encodeURIComponent(token)}`
      }
    })

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`删除失败: ${errorText}`)
    }

    ElMessage.success('删除成功')
    fetchJobs()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message)
    }
  } finally {
    loading.value = false;
  }
}

// 返回主页
const goToHome = () => {
  router.push('/')
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 获取用户信息
const fetchUserInfo = async (userId) => {
  try {
    const token = authStore.token
    const res = await fetch(`http://127.0.0.1:8000/api/users/${userId}`, {
      headers: { 'Authorization': `Bearer ${encodeURIComponent(token)}` }
    })
    if (!res.ok) throw new Error(await res.text())
    const userData = await res.json()
    userNames.value[userId] = userData.username
  } catch (err) {
    console.error('获取用户信息失败:', err)
    userNames.value[userId] = `用户${userId}` // 如果获取失败，显示默认名称
  }
}

// 获取指定岗位的申请
const fetchApplications = async (jobId) => {
  try {
    loading.value = true
    const token = authStore.token
    const res = await fetch(`http://127.0.0.1:8000/api/applications?job_id=${jobId}`, {
      headers: { 'Authorization': `Bearer ${encodeURIComponent(token)}` }
    })
    if (!res.ok) throw new Error(await res.text())
    applications[jobId] = await res.json()
    
    // 获取所有申请人的用户名
    for (const app of applications[jobId]) {
      await fetchUserInfo(app.applicant_id)
    }
  } catch (err) {
    ElMessage.error('获取申请失败: ' + err.message)
  } finally {
    loading.value = false
  }
}

// 切换申请列表展开
const toggleApps = (jobId) => {
  expanded[jobId] = !expanded[jobId]
  if (expanded[jobId] && !applications[jobId]) fetchApplications(jobId)
}

// 更新申请状态
const updateAppStatus = async (appId, status) => {
  try {
    loading.value = true
    const token = authStore.token
    const res = await fetch(`http://127.0.0.1:8000/api/applications/${appId}?user_id=${authStore.userId}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${encodeURIComponent(token)}` },
      body: JSON.stringify({ status })
    })
    if (!res.ok) throw new Error(await res.text())
    ElMessage.success('状态更新成功')
  } catch (err) {
    ElMessage.error('更新失败: ' + err.message)
  } finally {
    loading.value = false
    // 刷新当前申请列表
    Object.keys(expanded).forEach(jid => { if (expanded[jid]) fetchApplications(jid) })
  }
}

// 查看求职者简历
const viewResume = async (userId) => {
  try {
    loading.value = true
    const token = authStore.token
    const res = await fetch(`http://127.0.0.1:8000/api/job-seeker-profiles?user_id=${userId}`, {
      headers: { 'Authorization': `Bearer ${encodeURIComponent(token)}` }
    })
    if (!res.ok) throw new Error(await res.text())
    const data = await res.json()
    selectedResume.value = data[0] || null
    resumeDialogVisible.value = true
  } catch (err) {
    ElMessage.error('获取简历失败: ' + err.message)
  } finally {
    loading.value = false
  }
}

// 打开消息对话框
const openMessageDialog = (userId, jobId) => {
  messageForm.value.content = ''
  messageDialogVisible.value = true
  selectedResume.value = { 
    user_id: userId,
    job_id: jobId
  }
}

// 发送消息
const sendMessage = async () => {
  if (!messageForm.value.content) {
    ElMessage.warning('请输入消息内容')
    return
  }
  try {
    loading.value = true
    const token = authStore.token
    const res = await fetch(`http://127.0.0.1:8000/api/messages?sender_id=${authStore.userId}&receiver_id=${selectedResume.value.user_id}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${encodeURIComponent(token)}`
      },
      body: JSON.stringify({
        receiver_id: selectedResume.value.user_id,
        content: messageForm.value.content,
        related_job_id: selectedResume.value.job_id
      })
    })
    if (!res.ok) throw new Error(await res.text())
    ElMessage.success('消息发送成功')
    messageDialogVisible.value = false
    messageForm.value.content = ''
  } catch (err) {
    ElMessage.error('发送失败: ' + err.message)
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchJobs()
})
</script>

<style scoped>
.job-posting-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.action-bar {
  margin-bottom: 30px;
  display: flex;
  justify-content: space-between;
}

.action-button {
  padding: 12px 24px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.2);
}

.job-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 25px;
}

.job-card {
  height: 100%;
  transition: transform 0.3s;
  border-radius: 10px;
  overflow: hidden;
}

.job-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.job-title {
  font-weight: bold;
  font-size: 18px;
  color: #409EFF;
}

.card-actions {
  display: flex;
  gap: 10px;
}

.card-button {
  transition: all 0.3s ease;
  font-weight: 500;
  padding: 6px 16px;
  border-radius: 6px;
}

.edit-btn:hover {
  background-color: #66b1ff;
  color: white;
}

.delete-btn:hover {
  background-color: #f56c6c;
  color: white;
}

.card-content {
  font-size: 14px;
  line-height: 1.6;
  padding: 10px 5px;
}

.card-content p {
  margin: 10px 0;
}

.job-description, .job-requirements {
  margin-top: 15px;
}

.description-text {
  white-space: pre-line;
  color: #606266;
  margin-top: 4px;
  font-size: 13px;
  line-height: 1.5;
  max-height: 100px;
  overflow: hidden;
}

.update-time {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 10px;
}

.cancel-btn, .save-btn {
  padding: 10px 24px;
  font-size: 16px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background-color: #f2f6fc;
}

.save-btn:hover {
  opacity: 0.9;
}

.job-dialog :deep(.el-form-item__label) {
  font-weight: 500;
}

.application-section {
  margin-top: 20px;
}
</style>